const { query } = require('../../../lib/db');
const { authenticateToken } = require('../../../lib/auth');

async function handler(req, res) {
  try {
    switch (req.method) {
      case 'GET':
        return await getProductCategories(req, res);
      default:
        return res.status(405).json({
          success: false,
          message: '方法不允许'
        });
    }
  } catch (error) {
    console.error('产品分类API错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

async function getProductCategories(req, res) {
  const { 
    level, 
    parent_id, 
    status = '1',
    include_children = 'false'
  } = req.query;
  
  let sql = `
    SELECT pc.*, parent.name as parent_name
    FROM product_categories pc
    LEFT JOIN product_categories parent ON pc.parent_id = parent.id
    WHERE 1=1
  `;
  
  const params = [];
  
  if (level) {
    sql += ' AND pc.level = ?';
    params.push(level);
  }
  
  if (parent_id) {
    sql += ' AND pc.parent_id = ?';
    params.push(parent_id);
  }
  
  if (status) {
    sql += ' AND pc.status = ?';
    params.push(status);
  }
  
  sql += ' ORDER BY pc.level, pc.sort_order, pc.name';
  
  const categories = await query(sql, params);
  
  // 如果需要包含子分类
  if (include_children === 'true') {
    for (let category of categories) {
      if (category.level < 3) { // 最多3级分类
        const children = await query(`
          SELECT * FROM product_categories 
          WHERE parent_id = ? AND status = 1
          ORDER BY sort_order, name
        `, [category.id]);
        category.children = children;
      }
    }
  }
  
  res.status(200).json({
    success: true,
    data: categories
  });
}

export default authenticateToken(handler);